package xmu.crms.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import xmu.crms.config.security.SecurityConstant;

import java.math.BigInteger;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

/**
 *
 * @author status200
 * @date 2017/12/24
 */
public class JwtUtil {

    /**
     *  jwt加密秘钥
     */
    public static String pwdkey = "I love ooad";

    /**
     * jwt加密算法
     */
    public static SignatureAlgorithm mySignatureAlgorithm = SignatureAlgorithm.HS256;

    /**
     * 产生jwt
     *
     * @param claims
     * @return
     */
    public static String generateToken(Map<String,Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(generateExpirationDate())
                .signWith(mySignatureAlgorithm,pwdkey)
                .compact();
    }

    /**
     * 设置jwt有效时间为1个月
     *
     * @return
     */
    public static Date generateExpirationDate() {

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        //设置一个月过期
        calendar.add(Calendar.MONTH,1);

        return calendar.getTime();
    }

    /**
     * 解析AuthString获得数据
     *
     * @param authString
     * @return
     */
    public static Claims getClaimsFromAuthString(String authString) {
        String token = authString.substring(SecurityConstant.JWT_HEADER_PREFIX.length());

        return getClaimsFromToken(token);
    }

    /**
     * 解析token并得到数据
     *
     * @param token
     * @return 类似key value的Map
     */
    public static Claims getClaimsFromToken(String token) {

        Claims claims;
        try {
            claims = Jwts
                    .parser()
                    .setSigningKey(pwdkey)
                    .parseClaimsJws(token)
                    .getBody();

        } catch (Exception e) {
            claims = null;
        }
        return claims;
    }

    /**
     * 从token中获取用户的id
     *
     * @param token
     * @return
     */
    public static BigInteger getIdFromToken(String token) {

        Claims claims = getClaimsFromToken(token);

        return new BigInteger(String.valueOf(claims.get("id", Integer.class)));
    }


    /**
     * 从header的Authorization String里获得id
     *
     * @param authString 从header中得到的Authorization String
     * @return 用户的id
     */
    public static BigInteger getIdFromAuthString(String authString) {

        String token = authString.substring(SecurityConstant.JWT_HEADER_PREFIX.length());

        return getIdFromToken(token);
    }
}
